﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using Yxinmt.Interface;
using Yxinmt.Utility;

namespace Yxinmt.Windows.Meeting
{
    public class DocumentViewing : BaseWindow, IWindow
    {
        public Guid MeetingId { get; set; }

        public Dictionary<string,object> _TabNameProperty { get; set; }

        public Index _Index { get; set; }

        public Entity.FileInfo _File { get; set; }

        public DocumentViewing(System.Windows.Window form, IWindow parentWindow, System.Windows.Controls.Grid pagePanel, Dictionary<string, object> parameters)
        {
            Window = form;
            _PagePanel = pagePanel;
            _Parameters = parameters;
            ParentWindow= parentWindow;
            _Index = parentWindow as Index;
            MeetingId = _Parameters.GetValue<Guid>("MeetingId");
            _File = _Parameters.GetValue<Entity.FileInfo>("File");
            ClientConfig = _Index.ClientConfig;
            UserInfo = _Index.UserInfo;

            InitSet();

            initView();

            this.SetWindow();

            initLoad();
        }

        void initView()
        {
            var properties = _View.GetValue<List<Dictionary<string, object>>>("properties");
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
            foreach (var p in properties)
            {
                var name = p.GetStringValue("name");
                if (name == "TabNamePanel3") _TabNameProperty = p;
                else list.Add(p);
            }
            _View["properties"] = list;

            var p2 = Utility.Common.GetProperty(_View, "ShareScreen");
            p2 = Utility.Common.GetProperty(p2, "Label2");
            p2["Label"] = _Index.IsPublish ? "结束共享" : "共享";
        }

        public Entity.ClientConfig ClientConfig { get; set; }
        public Entity.UserInfo UserInfo { get; set; }

        public override void DataLoad()
        {
            if (_File != null) AddTab(_File);
        }

        List<Controls.StackPanelButton> _RightMenuButtonList { get; set; }

        public void OpenFile(IControl ctl)
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters["MeetingId"] = MeetingId;
            parameters["VideoFormatList"] = UserInfo.VideoFormatList;
            var mainWindow = new MainWindow(GetNewWindow(), "SelectFile", this, parameters);
            mainWindow.ShowDialog(() =>
            {
                var selectFile = mainWindow.CurrentWindow as SelectFile;
                AddTab(selectFile.SelectSubjectFile);
            });
        }

        IControl _RightArrow { get; set; }
        IControl _LeftArrow { get; set; }
        IControl _RightMenuPanel { get; set; }

        public List<Windows.Tab> TabList { get; set; }

        IComponent _TabNamePanels { get; set; }

        Controls.Grid _TabContentPanel { get; set; }

        IComponent _RightPropertyPanel { get; set; }

        int _Count { get; set; }

        Controls.StackPanelButton _ShareScreen { get; set; }
        void initLoad()
        {
            TabList = new List<Tab>();
            _RightArrow = GetControl("RightArrow");
            _LeftArrow = GetControl("LeftArrow");
            _RightMenuPanel = GetControl("RightMenuPanel");
            _TabNamePanels = GetComponent("TabNamePanels");
            _TabContentPanel = (Controls.Grid)GetControl("TabContentPanel");
            _RightPropertyPanel = GetComponent("RightPropertyPanel");

            _RightMenuButtonList = new List<Controls.StackPanelButton>();

            var rightMenuPanel2 = GetComponent("RightMenuPanel2");

            rightMenuPanel2.ComponentList.ForEach(c =>
            {
                foreach (var ctl in c.ControlList)
                {
                    if (ctl is Controls.StackPanelButton btn) _RightMenuButtonList.Add(btn);
                    if (ctl.Property.GetStringValue("name") == "ShareScreen") _ShareScreen = (Controls.StackPanelButton)ctl;
                }
            });
        }

        Windows.Tab _SelecTab { get; set; }

        public void CreateRecord(IControl ctl)
        {
            Entity.FileInfo file = new Entity.FileInfo();
            file.FileId = Guid.NewGuid();
            file.FileType = ".pdf";
            file.FileName = $"新建笔记{_Count+1}.pdf";
            file.RecordType = 3;
            file.IsNew = true;
           
            AddTab(file);
            saveRecord(file);
        }



        public void CreateNote(IControl ctl)
        {
            if (_SelecTab == null || _SelecTab.File.RecordType > 0) return;

            Entity.FileInfo file = new Entity.FileInfo();
            file.FileId = Guid.NewGuid();
            file.FileName = $"新建批注{_Count + 1}.png";
            file.FileType = ".png";
            file.RecordType = 1;
            file.NoteFileId = _SelecTab.File.FileId;
            file.NoteFileImage = (_SelecTab.Window as FileReaderTab).GetCaptureScreenImage();
           
            AddTab(file);
            saveRecord(file);
        }

        public void CreateWhiteboard(IControl ctl)
        {
            Entity.FileInfo file = new Entity.FileInfo();
            file.FileId = Guid.NewGuid();
            file.FileType = ".png";
            file.FileName = $"新建白板{_Count + 1}.png";
            file.RecordType = 2;

            AddTab(file);
            saveRecord(file);
        }

        public void CloseTab(IControl ctl)
        {
            if (TabList.Count == 0) return;

            var tabId = ctl.Property.GetValue<Guid>("TabId");

            var tab = tabId == Guid.Empty || tabId == _SelecTab.Id ? _SelecTab : TabList.Where(w => w.Id == tabId).FirstOrDefault();
            if (tab != null)
            {
                removeTab(tab);
                if (tab.Id == _SelecTab.Id) this.SetSelectTabWindow(_SelecTab.SelectFileTab ?? TabList.LastOrDefault());
                setButtonsEnabled();
            }
        }

        public void CloseTabByFileId(Guid fileId)
        {
            var tab = _SelecTab != null && _SelecTab.File.FileId == fileId ? _SelecTab : TabList.Where(w => w.File.FileId == fileId).FirstOrDefault();
            if (tab != null)
            {
                removeTab(tab);
                if (tab.Id == _SelecTab.Id) this.SetSelectTabWindow(_SelecTab.SelectFileTab ?? TabList.LastOrDefault());
                setButtonsEnabled();
            }
        }

        public void AllCloseTab(IControl ctl)
        {
            if (TabList.Count == 0) return;

            TabList.ForEach(tab =>
            {
                tab.Window.CloseWindow();
                _TabNamePanels.Remove(tab.Property);
                _TabContentPanel.Remove(tab.Window.Grid);
            });

            _SelecTab = null;
            TabList = new List<Tab>();
            setButtonsEnabled();
        }

        void removeTab(Windows.Tab tab)
        {
            tab.Window.CloseWindow();
            _TabNamePanels.Remove(tab.Property);
            TabList.Remove(tab);
            _TabContentPanel.Remove(tab.Window.Grid);
        }

        public void AddTab(Entity.FileInfo file)
        {
            try
            {
                if (TabList.Count >= 20)
                {
                    this.Alert("最多可创建20个Tab页");
                    return;
                }

                if (_SelecTab != null && _SelecTab.File.FileId == file.FileId) return;

                var tab = TabList.Where(w=>w.File.FileId == file.FileId).FirstOrDefault();
                if (tab != null)
                {
                    Save(null);
                    this.SetSelectTabWindow(tab);
                    setButtonsEnabled();
                    return;
                }

                _Count += 1;

                tab = new Windows.Tab(file.Name);

                tab.Property = Utils.CloneDictionary(_TabNameProperty);

                tab.Property["BackColor"] = tab.Property["SelectedBackColor"];
                tab.Property["id"] = tab.Id;
                tab.File = file;

                var property = Utility.Common.GetProperty(tab.Property, "TabName");
                property["Text"] = tab.Label;
                property["name"] = tab.Name;
                property["TabId"] = tab.Id;
                property["EventActionName"] = "SetSelectTab";

                property = Utility.Common.GetProperty(tab.Property, "DeleteFile");
                property["name"] = string.Format("Delete{0}", tab.Name);
                property["TabId"] = tab.Id;

                if (tab.File.RecordType == 1) tab.SelectFileTab = _SelecTab;

                SetSelectTabWindow(null);
                TabList.Add(tab);
        
                _SelecTab = tab;
                _RightPropertyPanel.SetVisible(_SelecTab.File.RecordType == 1 || _SelecTab.File.RecordType == 2);

                tab.TabNamePanel = _TabNamePanels.Add(tab.Property);
                tab.TextBox = GetControl(tab.TextBox, tab.Name) as Controls.ImageTextButton;

                addTabContentPanel(tab, file);

                setButtonsEnabled();
            }
            catch(Exception ex)
            {
                Alert(Name, "addTab", ex);
            }
        }

        void saveRecord(Entity.FileInfo file)
        {
            TaskRun("SaveFile", true, () =>
            {
                var record = new Dictionary<string, object>();
                if (file.NoteFileId != Guid.Empty)
                {
                    record["FileId"] = file.NoteFileId;

                    string urlName = file.FileId.ToString() + "_bg.png";
                    string dirName = MeetingId.ToString() + "/" + file.RecordTypeName;

                    var res2 = RequestService.UploadFile(file.FileName, dirName, urlName, file.NoteFileImage);
                    if (!res2.Result)
                    {
                        Alert(res2.Message);
                        return;
                    }

                    record["FileUrl"] = res2.FileUrl;
                }
                record["RecordId"] = file.FileId;
                record["FileName"] = file.FileName;
                record["RecordType"] = file.RecordType;
                record["MeetingId"] = MeetingId;
                record["FileType"] = file.FileType;

                var res = RequestService.SaveRecord(record, false);
                if (!res.Result) Alert(res.Message);
            });
        }

        void setButtonsEnabled()
        {
            _RightMenuButtonList.ForEach(b =>
            {
                if (b.Name == "Close" || b.Name == "AllClose") b.SetEnabled(_SelecTab != null);
                else if (b.Name == "ReName") b.SetEnabled(_SelecTab != null && _SelecTab.File.RecordType > 0);
                else if (b.Name == "CreateNote")
                {
                    b.SetEnabled(_SelecTab != null && _SelecTab.File.RecordType == 0);
                }
                else if (b.Name == "Save")
                {
                    b.SetEnabled(_SelecTab != null && _SelecTab.File.RecordType > 0);
                }
            });
        }

        public void Save(IControl ctl)
        {
            if (_SelecTab == null) return;

            if (_SelecTab.Window is CreateRecord record) record.Save();
            else if (_SelecTab.Window is InkCanvasTab ink) ink.Save();
        }

        public void SetSelectTab(IControl ctl)
        {
            var tabId = ctl.Property.GetValue<Guid>("TabId");
            if (tabId == _SelecTab.Id) return;

            var tab = TabList.Where(w => w.Id == tabId).FirstOrDefault();
            if (tab != null)
            {
                Save(ctl);
                this.SetSelectTabWindow(tab);
                setButtonsEnabled();
            }
        }

        void SetTextBlur(Controls.TextBox textBox)
        {
            textBox.SetEdit(false);
            textBox.SetBackColor("Transparent");
            string fontColor = textBox.Equals(_SelecTab.TextBox) ? textBox.Property.GetStringValue("SelectedFontColor") : textBox.Property.GetStringValue("UnSelectedFontColor");
            textBox.SetFontColor(fontColor);
        }

        void addTabContentPanel(Windows.Tab tab, Entity.FileInfo file)
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters["File"] = file;

            if (file.RecordType == 1) tab.Window = new InkCanvasTab(this.Window, this, _TabContentPanel.Element as System.Windows.Controls.Grid, parameters);
            else if (file.RecordType == 2) tab.Window = new InkCanvasTab(this.Window, this, _TabContentPanel.Element as System.Windows.Controls.Grid, parameters);
            else if (file.RecordType == 3) tab.Window = new CreateRecord(this.Window, this, _TabContentPanel.Element as System.Windows.Controls.Grid, parameters);
            else tab.Window = new FileReaderTab(this.Window, this, _TabContentPanel.Element as System.Windows.Controls.Grid, parameters);

            tab.Window.GridPageLoad();
        }

        void SetSelectTabWindow(Windows.Tab tab)
        {
            if (tab == null) _SelecTab = null;

            TabList.ForEach(t =>
            {
                string fontColor = string.Empty;
                string backColor = string.Empty;

                if (tab != null && t.Id == tab.Id)
                {
                    t.Selected = true;
                    backColor = t.Property.GetStringValue("SelectedBackColor");
                    fontColor = t.TextBox.Property.GetStringValue("SelectedFontColor");
                    _SelecTab = t;
                }
                else
                {
                    t.Selected = false;
                    backColor = t.Property.GetStringValue("UnSelectedBackColor");
                    fontColor = t.TextBox.Property.GetStringValue("UnSelectedFontColor");
                    t.Window.Grid.Visibility = System.Windows.Visibility.Collapsed;
                }

                t.TextBox.SetFontColor(fontColor);
                t.TabNamePanel.SetBackColor(backColor);
            });

            if (_SelecTab != null)
            {
                _SelecTab.Window.ShowLoad();
                _SelecTab.Window.Grid.Visibility = System.Windows.Visibility.Visible;

                _RightPropertyPanel.SetVisible(_SelecTab.File.RecordType == 1 || _SelecTab.File.RecordType == 2);
            }
        }

        public void ReName(IControl ctl)
        {
            if (_SelecTab == null) return;

            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters["File"] = _SelecTab.File;
            if (_SelecTab.File.RecordType == 0) return;
            var mainWindow = new MainWindow(GetNewWindow(), "Rename", this, parameters);
            mainWindow.ShowDialog(() =>
            {
                var rename = mainWindow.CurrentWindow as Rename;
                _SelecTab.File.FileName = rename.FileName;
                _SelecTab.TextBox.SetLabelText(_SelecTab.File.Name);
            });
        }

        public void SetRightArrow(IControl ctl)
        {
            SetRightPanelVisible(false);
        }
        public void SetLeftArrow(IControl ctl)
        {
            SetRightPanelVisible(true);
        }

        void SetRightPanelVisible(bool blVisible)
        {
            _RightMenuPanel.SetVisible(blVisible);
            _RightPropertyPanel.SetVisible(blVisible && _SelecTab != null && _SelecTab.File.RecordType >= 1 && _SelecTab.File.RecordType <= 2);
            _RightArrow.SetVisible(blVisible);
            _LeftArrow.SetVisible(!blVisible);
        }

        public void LockScreen(IControl ctl)
        {
            openWebPage("lockScreen");
        }

        public void ShareScreen(IControl ctl)
        {
            openWebPage("shareScreen");
        }

        void openWebPage(string name)
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            var url = _Index.GetWebUrl(name);
            parameters["Url"] = url + "&MeetingId=" + MeetingId.ToString();
            parameters["Index"] = _Index;
            var mainWindow = new MainWindow(GetNewWindow(), "WebPage", this, parameters);
            mainWindow.ShowDialog();
        }

        public void ToBack(IControl ctl)
        {
            _Index.DocumnetViewingToBack();
        }

        public void SetShareText(bool isPublish)
        {
            _ShareScreen.SetLabelText(isPublish ? "结束共享" : "共享");
        }
    }
}
